#!/bin/bash

# A script to perform incremental backups using rsync

set -o errexit
set -o nounset
set -o pipefail


start_time=$(date +%s)
echo "备份脚本开始执行..."

#readonly SOURCE_DIR="lihao@192.168.101.118:/home/lihao/nginx_work/doc_1/20240226/doc_1/"
readonly SOURCE_DIR="lihao@lyw.cdbytech.top:/home/lihao/nginx_work/doc_1/20240226/doc_1/"
#readonly BACKUP_DIR="/home/lihao/sda/backup"
readonly BACKUP_DIR="/home/lihao/backup"
readonly DATETIME="$(date '+%Y-%m-%d_%H:%M:%S')"
readonly BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
readonly LATEST_LINK="${BACKUP_DIR}/latest"

mkdir -p "${BACKUP_DIR}"

# 参数说明
#   采用-a（归档模式）、
#   -v（详细信息）、
#   -z（压缩）、
#   -P（显示进度）和
#   --delete（同步删除）选项
# rsync -avzP --delete --rsh=ssh \
rsync -avzP --delete --rsh="ssh -i ~/.ssh/backup_key" \
  "${SOURCE_DIR}/" \
  --link-dest "${LATEST_LINK}" \
  --exclude=".cache" \
  "${BACKUP_PATH}"

# 说明
# 自动输入密码的rsync备份脚本 （ --rsh="ssh -i ~/.ssh/backup_key" ）
# 操作步骤
#  1、生成SSH密钥对
#    ssh-keygen -t rsa -b 4096 -f ~/.ssh/backup_key
#  2、将公钥复制到目标服务器
#    ssh-copy-id -i ~/.ssh/backup_key.pub lihao@lyw.cdbytech.top

rm -rf "${LATEST_LINK}"
ln -s "${BACKUP_PATH}" "${LATEST_LINK}"

echo "备份脚本执行完毕..."

end_time=$(date +%s)
execution_time=$((end_time - start_time))

hours=$((execution_time / 3600))
minutes=$(( (execution_time % 3600) / 60 ))
seconds=$((execution_time % 60))

# 使用 printf 补零
printf "备份脚本执行时间: %02d 小时 %02d 分钟 %02d 秒\n" $hours $minutes $seconds

# ln -s /home/lihao/sda/backup/20240918/doc /home/lihao/sda/backup/latest